package com.liit.controller.func;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.liit.weixin.core.basic.accesstoken.AccessTokenSupport;
import cn.liit.weixin.templatemsg.utils.MsgUtil;

import com.liit.annotation.SystemLog;
import com.liit.controller.index.BaseController;
import com.liit.entity.CodeFormMap;
import com.liit.entity.DictFormMap;
import com.liit.entity.OrgInfoFormMap;
import com.liit.entity.PartyFormMap;
import com.liit.entity.UserFormMap;
import com.liit.entity.UserRoleFormMap;
import com.liit.entity.WeixinUserFormMap;
import com.liit.mapper.CodeMapper;
import com.liit.mapper.DictMapper;
import com.liit.mapper.OrgInfoMapper;
import com.liit.mapper.PartyMapper;
import com.liit.mapper.UserMapper;
import com.liit.mapper.WeixinUserMapper;
import com.liit.plugin.PageView;
import com.liit.util.Common;
import com.liit.util.DictUtils;
import com.liit.util.JsonUtils;
import com.liit.util.POIUtils;
import com.liit.util.PropertiesUtils;
import com.liit.util.RegionUtils;

/**
 * 
 * @author dingweibo
 * @Title: OrgController.java
 * @Description: 组织操作
 * @date 2016年3月29日
 */
@Controller
@RequestMapping("/org/")
public class OrgController extends BaseController {
	@Inject
	private OrgInfoMapper orgInfoMapper;

	@Inject
	private CodeMapper codeMapper;

	@Inject
	private UserMapper userMapper;

	@Inject
	private WeixinUserMapper weixinUserMapper;
	@Inject
	private PartyMapper partyMapper;
	@Inject
	private DictMapper dictMapper;

	@RequestMapping("listApplying")
	public String listUI(Model model) throws Exception {
		model.addAttribute("res", findByRes());
		model.addAttribute("dict", DictUtils.getDictByType("SQZT"));
		return Common.BACKGROUND_PATH + "/func/listOrgApplying";
	}

	@RequestMapping("list")
	public String listHis(Model model) throws Exception {
		model.addAttribute("res", findByRes());
		model.addAttribute("dict", DictUtils.getDictByType("SQZT"));
		model.addAttribute("orgType", DictUtils.getDictByType("ORG_TYPE"));
		return Common.BACKGROUND_PATH + "/func/listOrg";
	}

	@ResponseBody
	@RequestMapping("findByApplyingPage")
	public PageView findByApplyingPage(String pageNow, String pageSize) throws Exception {
		OrgInfoFormMap orgInfoFormMap = getFormMap(OrgInfoFormMap.class);
		orgInfoFormMap.put("status", Common.ORG_STATUS_APPLY);// 申请中
		Common.addRoleParameter(orgInfoFormMap);
		Common.trimMap(orgInfoFormMap);
		orgInfoFormMap = toFormMap(orgInfoFormMap, pageNow, pageSize, orgInfoFormMap.getStr("orderby"));
		pageView.setRecords(orgInfoMapper.findByPage(orgInfoFormMap));
		return pageView;
	}

	@ResponseBody
	@RequestMapping("findByPage")
	public PageView findByPage(String pageNow, String pageSize) throws Exception {
		OrgInfoFormMap orgInfoFormMap = getFormMap(OrgInfoFormMap.class);
		Common.addRoleParameter(orgInfoFormMap);
		Common.trimMap(orgInfoFormMap);
		orgInfoFormMap.put("where","status!="+Common.ORG_STATUS_APPLY+"");
		orgInfoFormMap = toFormMap(orgInfoFormMap, pageNow, pageSize, orgInfoFormMap.getStr("orderby"));
		pageView.setRecords(orgInfoMapper.findByPage(orgInfoFormMap));
		return pageView;
	}
	@RequestMapping("/exportOrg")
	public void exportOrg(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String fileName = "机构信息";
		OrgInfoFormMap orgInfoFormMap  = findHasHMap(OrgInfoFormMap.class);
		String exportData = orgInfoFormMap.getStr("exportData");// 列表头的json字符串
		List<Map<String, Object>> listMap = JsonUtils.parseJSONList(exportData);
		Common.addRoleParameter(orgInfoFormMap);
		Common.trimMap(orgInfoFormMap);
		listMap.remove(0);
		orgInfoFormMap.put("where","status!="+Common.ORG_STATUS_APPLY+"");
		List<OrgInfoFormMap> partys=orgInfoMapper.findByWhere(orgInfoFormMap);
		if(partys.size()>0){
			for(int i=0;i<partys.size();i++){
				
				DictFormMap dform=new DictFormMap();
				dform.put("type", "ORG_TYPE");
				dform.put("value",partys.get(i).get("orgType"));
				
				if(!"".equals(partys.get(i).get("orgType"))&&partys.get(i).get("orgType")!=null){
					partys.get(i).put("orgType",dictMapper.findByWhere(dform).get(0).get("label"));
				}
				
				dform.put("type","SQZT");
				dform.put("value",partys.get(i).get("status"));
				partys.get(i).put("status", dictMapper.findByWhere(dform).get(0).get("label"));
				
			}
		}
		POIUtils.exportToExcel(response, listMap, partys, fileName);
	}
	@ResponseBody
	@RequestMapping("pass")
	@Transactional(readOnly = false)
	@RequiresPermissions("org:check:pass")
	@SystemLog(module = "机构管理", methods = "机构审核-审核通过")
	public String pass(String ids) throws Exception {
		logger.info("org pass param:" + ids);
		Timestamp now = new Timestamp(System.currentTimeMillis());
		String[] idss = ids.split(",");
		OrgInfoFormMap record = new OrgInfoFormMap();
		for (String id : idss) {
			record.put("id", id);
			record.put("status", Common.ORG_STATUS_PASS);
			record.put("updateTime", now);
			record.put("accountName", SecurityUtils.getSubject().getPrincipal());
			orgInfoMapper.editEntity(record);

			// 生成邀请码
			int codeNum = DictUtils.getFirstDictValue("CODE_NUMBER");
			for (int i = 0; i < codeNum; i++) {

				String code = null;
				do {
					code = Common.getStringRandom(6);// 邀请码长度6位
				} while (!CollectionUtils.isEmpty(codeMapper.findByAttribute("code", code, CodeFormMap.class)));

				CodeFormMap codeFormMap = new CodeFormMap();
				codeFormMap.put("orgInfoId", id);
				codeFormMap.put("code", code);
				codeFormMap.put("createTime", now);
				codeMapper.addEntity(codeFormMap);
			}
			WeixinUserFormMap weixinUser = new WeixinUserFormMap();
			weixinUser.put("regType", Common.USER_REG_TYPE_ORG);
			weixinUser.put("orgInfoId", id);

			weixinUser = weixinUserMapper.findByWhere(weixinUser).get(0);

			UserFormMap userMap = new UserFormMap();
			userMap.put("openid", weixinUser.get("openid"));

			userMap = userMapper.findByNames(userMap).get(0);
			userMap.put("locked", Common.COMMON_NO);
			userMap.put("deletestatus", Common.COMMON_NO);
			userMapper.editEntity(userMap);
			// 用户赋权
			UserRoleFormMap userRole = new UserRoleFormMap();
			userRole.put("userId", userMap.getInt("id"));
			userRole.put("roleId", 3);// 微信机构用户
			userMapper.addEntity(userRole);
			
			// 发送模板消息
			sendTemplateMsg(weixinUser.getStr("openid"), "", orgInfoMapper.findbyFrist("id", id, OrgInfoFormMap.class));
		}
		return "success";
	}

	@ResponseBody
	@RequestMapping("reject")
	@Transactional(readOnly = false)
	@RequiresPermissions("org:check:reject")
	@SystemLog(module = "机构管理", methods = "机构审核-审核拒绝")
	public String reject(String ids) throws Exception {
		logger.info("org reject param:" + ids);
		Timestamp now = new Timestamp(System.currentTimeMillis());
		OrgInfoFormMap record = new OrgInfoFormMap();
		String[] idss = ids.split(",");
		for (String id : idss) {
			record.put("id", id);
			record.put("status", Common.ORG_STATUS_REJECT);
			record.put("updateTime", now);
			record.put("accountName", SecurityUtils.getSubject().getPrincipal());
			orgInfoMapper.editEntity(record);

			// 删除用户
			OrgInfoFormMap orgInfoFormMap = orgInfoMapper.findbyFrist("id", id, OrgInfoFormMap.class);
			String openid = orgInfoFormMap.getStr("openid");
			UserFormMap user = weixinUserMapper.findbyFrist("openid", openid, UserFormMap.class);
			logger.info("org refuse and delete user:" + user);
			weixinUserMapper.deleteByAttribute("id", user.get("id").toString(), UserFormMap.class);
			// 删除用户角色
			weixinUserMapper.deleteByAttribute("userId", user.get("id").toString(), UserRoleFormMap.class);
			
			// 发送模板消息
			sendTemplateMsg(openid, "", orgInfoFormMap);
		}
		return "success";
	}

	@RequestMapping("viewUI")
	public String findByPage(Model model, String id) throws Exception {
		OrgInfoFormMap record = orgInfoMapper.findbyFrist("id", id, OrgInfoFormMap.class);
		record.put("province", RegionUtils.getRegionNameById(record.getStr("province")));
		record.put("city", RegionUtils.getRegionNameById(record.getStr("city")));
		record.put("area", RegionUtils.getRegionNameById(record.getStr("area")));
		record.put("street", RegionUtils.getRegionNameById(record.getStr("street")));

		if (record.get("orgType") != null) {
			record.put("orgType", DictUtils.getDictByValue("ORG_TYPE", record.getInt("orgType")).get("label"));
		}
		model.addAttribute("orgInfo", record);

		WeixinUserFormMap wxUser = orgInfoMapper.findbyFrist("openid", record.getStr("openid"), WeixinUserFormMap.class);
		wxUser.put("province", RegionUtils.getRegionNameById(record.getStr("province")));
		wxUser.put("city", RegionUtils.getRegionNameById(record.getStr("city")));
		wxUser.put("area", RegionUtils.getRegionNameById(record.getStr("area")));
		wxUser.put("street", RegionUtils.getRegionNameById(record.getStr("street")));
		model.addAttribute("wxUser", wxUser);
		return Common.BACKGROUND_PATH + "/func/viewOrg";
	}
	/**
	 * 删除机构信息
	 * 
	 */
	@ResponseBody
	@RequestMapping("deleteEntity")
	// 需要事务操作必须加入此注解
	@Transactional(readOnly = false)
	// 凡需要处理业务逻辑的.都需要记录操作日志
	@SystemLog(module = "机构管理", methods = "删除机构")
	@RequiresRoles(value = { "admin" })
	public String deleteEntity() throws Exception {
		String[] ids = getPara("ids").split(",");
		Boolean isTrue=false;
		for (String id : ids) {
			PartyFormMap party = new PartyFormMap();
			party.put("orgInfoId", id);
			List<PartyFormMap> pList=partyMapper.findByWhere(party);
			if(pList.size()>0){
				isTrue=true;
				break;
			}
		}
		if(isTrue){
			return "fail";
		}else{
			for (String id : ids) {
				WeixinUserFormMap weixinUser=new WeixinUserFormMap();
				weixinUser.put("orgInfoId",id);
				weixinUser=weixinUserMapper.findByWhere(weixinUser).get(0);
				
				UserFormMap user=new UserFormMap();
				user.put("openid", weixinUser.get("openid"));
				user=userMapper.findByWhere(user).get(0);
				
				userMapper.deleteByAttribute("userId", user.get(id).toString(), UserRoleFormMap.class);
				userMapper.deleteByAttribute("id", user.get(id).toString(),UserFormMap.class);
				
				weixinUser.put("orgInfoId",null);
				weixinUser.put("code",null);
				weixinUser.put("regType",0);
				
				weixinUserMapper.editEntity(weixinUser);
				codeMapper.deleteByAttribute("orgInfoId",id,CodeFormMap.class);
				orgInfoMapper.deleteByAttribute("id",id,OrgInfoFormMap.class);
				
			}
		   return "success";
		}
	}
	
	/**
	 * 发送机构审核模板消息
	 * 
	 * @param openid
	 * @param url
	 * @param orgInfoFormMap
	 */
	private static void sendTemplateMsg(String openid, String url, OrgInfoFormMap orgInfoFormMap) {
		String first = null;
		String[] keywords =null;
		if (orgInfoFormMap.getInt("status") == Common.ORG_STATUS_PASS) {
			first = "您好，恭喜您！您的机构注册信息已经通过审核。\\n\\n"
					+ "【G绿色伙伴】免费为社会组织提供线下活动的线上全流程服务（活动发布—报名—签到—评价等）。\\n\\n"
					+ "进入菜单【机构入口】——点击【活动发布】发布各类活动信息，点击【我的活动】查看、管理更方便！\\n\\n"
					+ "您的活动可能会被加精推荐哦，赶快行动起来吧！";
			keywords = new String[] { orgInfoFormMap.getStr("orgName"), "审核通过" };
		} else {
			first = "您好，您的机构注册信息未通过审核，原因可能是填写信息不完整、不真实；\\n\\n"
					+ "请您进入菜单【机构入口】——【机构信息】重新完善您的信息。\\n\\n"
					+ "【G绿色伙伴】免费为社会组织提供线下活动的线上全流程服务（活动发布—报名—签到—评价等）。\\n\\n"
					+ "若您有其他想要了解或咨询的问题，都可以用力输入，“绿色伙伴”将第一时间为您解答！ （报名、签到、评价、赚积分、换礼品......）";
			keywords = new String[] { orgInfoFormMap.getStr("orgName"), "审核拒绝" };
		}
		MsgUtil.sendTemplateMsg(AccessTokenSupport.getAccess_token(), openid, url, PropertiesUtils.findPropertiesKey("templateid.org"), first, keywords, "");
	}
}
